<template>
	<div class="global-variable">
		<lang></lang>
		<curr-app></curr-app>
		<list-title :data="header" @changeVisible="changeVisible"></list-title>
		<list-table :list="globalVariableList" :tableLoading="tableLoading" :footer="true" :pagination="pagination" :appid="$route.query.appid">
			<template v-slot:data>
				<el-table-column prop="variable_name" label="变量名称"></el-table-column>
				<el-table-column prop="variable_tag" label="标签名称"></el-table-column>
				<el-table-column prop="variable_val" label="变量值" show-overflow-tooltip :render-header="icons">
					<template slot-scope="scope">
						<el-input v-if="scope.row.flag == 1" type="textarea" :rows="2" maxlength="500" show-word-limit placeholder="请输入变量值" v-model="scope.row.variable_val" @blur="setVariableVal(scope.$index, scope.row)"></el-input>
						<upload-oss v-if="scope.row.flag == 2"
						:stsdomain="$domain.ac" 
						:ossdomain="$ossdomain" 
						:appid="$route.query.appid" 
						:limit="1" 
						:field="scope.$index" 
						:fileList="scope.row.variable_val" 
						:maxSize="20" 
						@insertFile="insertFile"
						@delFile="delFile">
						</upload-oss>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150">
					<template slot-scope="scope">
						<el-popover
						placement="top"
						width="160"
						v-model="scope.row.delTipStatus"  v-if="auth.delete">
							<p class="del-tip"><span class="el-icon-question"></span>确定删除吗？</p>
							<div style="text-align: right; margin: 0">
								<el-button size="mini" type="text" @click="scope.row.delTipStatus = false">取消</el-button>
								<el-button type="primary" size="mini" @click="handleDelete(scope.$index, scope.row)">确定</el-button>
							</div>
							<el-button type="text" slot="reference" :disabled='scope.row.delBtnStatus'>
								删除 <span class="el-icon-loading" v-if='scope.row.delBtnStatus'></span>
							</el-button>
						</el-popover>
						<el-button size='mini' type='text' class='tag-read' @click='getTag(scope.row)'>标签调用</el-button>
					</template>
				</el-table-column>
			</template>
		</list-table>
		<!-- 添加变量 开始 -->
		<el-dialog :title="dialogTitle" :visible.sync="header.dialogs[0].visible" :close-on-click-modal="false" width="460px">
			<el-form :model="variableForm" :rules="rules" ref="variableForm" label-width="100px">
				<el-form-item label="变量名称" prop="data.variable_name" style="width: 378px;">
					<el-input v-model="variableForm.data.variable_name" placeholder="变量名称"></el-input>
				</el-form-item>
				<el-form-item label="标签名称" prop="data.variable_tag" style="width: 378px;">
					<el-input v-model="variableForm.data.variable_tag" placeholder="标签名称"></el-input>
					<p class="help">用于前端模版标签调取，不能用汉字</p>
				</el-form-item>
				<el-form-item label="变量值" prop="data.variable_val" style="width: 378px;">
					<el-input v-model="variableForm.data.variable_val" placeholder="变量值"></el-input>
				</el-form-item>
				<el-form-item label="类型" prop="data.flag">
					<template>
						<el-radio v-model="variableForm.data.flag" label="1">文本</el-radio>
						<el-radio v-model="variableForm.data.flag" label="2">图片</el-radio>
					</template>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="header.dialogs[0].visible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('variableForm')" :disabled='variableForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='variableForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 添加变量 结束 -->
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import ListTable from "pc/common/ListTable"
import UploadOss from "pc/common/UploadOss"
import {judgeAuth} from "static/js/common.js"
import {mapGetters} from 'vuex'
import Clipboard from 'clipboard'
import Lang from "pc/common/Lang"
import CurrApp from "pc/common/CurrApp"

export default {
	inject: ['reload'],
	data() {
		var variableTag = (rule, value, callback) => {
			let reg = /^[a-zA-Z]([-_a-zA-Z0-9]{2,20})$/;
			if(!reg.test(value)){
				callback(new Error('必须为纯字母 或 字母+数字，并以字母开头'));
			} else {
				callback();
			}
		};
		return {
			/*appid*/
			appid: this.$route.query.appid,
			/*当前语言*/
			currlang: '',
			/*头部数据*/
			header: {
				title: '全局变量配置',
				reload: true,
				dialogs: [
					{
						title: '添加变量',
						type: 'primary',
						visible: false,
						auth: false,
					}
				]
			},
			auth: {
				editor: false,//编辑
				delete: false,//删除
			},
			dialogTitle: '添加变量',//dialog标题
			/*列表数据*/
			globalVariableList: [
				// {
				// 	id: 1,
				// 	app_id: 1,
				// 	variable_name: '',
				// 	variable_tag: '',
				// 	variable_val: '',
				// 	flag: 1,
				// 	delBtnStatus: false,//删除按钮状态
				// 	delTipStatus: false,//删除提示状态
				// },
			],
			pagination: {
				count: 0,
				currPage: 1,
				pageSize: 3
			},
			tableLoading: true,
			delTip: [],//刪除提示
			/*添加表单数据*/
			variableForm: {
				submitLock: false,
				data: {
					id: 0,
					variable_name: '',
					variable_tag: '',
					variable_val: '',
					flag: '1',
				}
			},
			rules: {
				data: {
					variable_name: [
						{ required: true, message: '请输入变量名称', trigger: 'blur' },
						{ min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' },
					],
					variable_tag: [
						{ required: true, message: '请输入标签名称', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' },
						{ validator: variableTag, trigger: 'blur' }
					]
				}
			}
		};
	},
	components: {
		ListTitle,
		ListTable,
		UploadOss,
		Lang,
		CurrApp
	},
	created: function() {
		/*获取当前语言*/
		let lang = this.$localstorage.get('lang');
		this.currlang = lang?lang:'zh'
		/*获取列表数据*/
		this.getVisibleList()
		/*权限判断显示*/
		this.header.dialogs[0].auth = (judgeAuth('addGlobalVariable', this.allMenuList) == undefined)?false:true
		this.auth.editor = (judgeAuth('modifyGlobalVariable', this.allMenuList) == undefined)?false:true
		this.auth.delete = (judgeAuth('delGlobalVariable', this.allMenuList) == undefined)?false:true
	},
	watch: {
		/*监听路由变化，根据参数查询数据*/
		'$route' (to){
			this.tableLoading = true
			this.getVisibleList()
		}
	},
	methods: {
		icons(h, {column}){
			const inReview = '直接在输入框中修改变量值，鼠标离开即可保存'
			return h(
				'div', [
					h('span', column.label),
					h('el-tooltip', {
						props: {
							placement: 'right'
						}
					}, [
						h('div', {
							slot: 'content',
							style: {
								'width': '150px',
								'whiteSpace': 'normal',
								'margin-bottom': '10px',
								'line-height': '20px',
								'height': '30px',
							}
						}, inReview),
						h('i', {
							class: 'el-icon-info',
							style: 'margin-left:5px; font-size: 12px'
						})
					],)
				]
			)
		},
		/*取出列表数据*/
		getVisibleList: function(){
			if(this.$api.globalVariableList != undefined){
				this.$baseURL(this.$domain.cms)
				this.$route.query.lang = this.currlang
				this.$get(this.$api.globalVariableList, this.$route.query).then(res => {
					// console.log(res);
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.globalVariableList = []
							let variable_val = ''
							Object.keys(res.data.data.list).forEach((k) => {
								if(res.data.data.list[k].flag == 1){//文本
									variable_val = res.data.data.list[k].variable_val
								}
								if(res.data.data.list[k].flag == 2){//图片
									if(res.data.data.list[k].variable_val == ""){
										variable_val = []
									}else{
										variable_val = [{name: '', url: res.data.data.list[k].variable_val}]
									}
								}
								this.globalVariableList.push ({
									id: res.data.data.list[k].id,
									app_id: res.data.data.list[k].app_id,
									variable_name: res.data.data.list[k].variable_name,
									variable_tag: res.data.data.list[k].variable_tag,
									variable_val: variable_val,
									flag: res.data.data.list[k].flag,
									delBtnStatus: false,//删除按钮状态
									delTipStatus: false,//删除提示状态
								});
							})
							// console.log(this.globalVariableList)
							this.pagination = res.data.data.pageInfo
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*dialog切换 方便子组件调用*/
		changeVisible: function(index){
			/*因为子组件调用的都是添加的行为，所以需要把app_cat_id置为0(方便判断是添加还是修改)，title改为'添加分类'*/
			this.dialogTitle = '添加变量'
			this.variableForm.data.id = 0

			this.header.dialogs[index].visible = !this.header.dialogs[index].visible
		},
		/*提交添加、修改表单*/
		submitForm(formName) {
			if(!this.variableForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.variableForm.submitLock = true;
						/*添加、修改分类*/
						let apiUrl = this.$api.addGlobalVariable//默认是添加
						if(this.variableForm.data.id > 0){//修改
							apiUrl = this.$api.modifyGlobalVariable
						}

						this.variableForm.data.lang = this.currlang

						if(apiUrl != undefined){
							this.$baseURL(this.$domain.cms)
							this.$post(apiUrl, {
								appid: this.appid,
								GlobalVariable: this.variableForm.data
							}).then(res => {
								console.log(res);
								/*成功*/
								if(res.data.code == 0){
									this.getVisibleList()
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'success'
									});

									if(this.variableForm.data.id > 0){
										this.reload();
									}else{
										this.$refs[formName].resetFields();
									}
								}else{
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'error'
									});
								}
								this.variableForm.submitLock = false;
							});
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*修改变量值*/
		setVariableVal(index, row) {
			this.$baseURL(this.$domain.cms)
			this.$post(this.$api.modifyGlobalVariable, {
				appid: this.appid,
				'GlobalVariable': {
					'id': row.id,
					'variable_val': row.variable_val
				}
			}).then(res => {
				if(res.data.code == 0){
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'success'
					});
				}else{
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'error'
					});
				}
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*删除*/
		handleDelete(index, row) {
			if(this.$api.delGlobalVariable != undefined){
				if(!this.globalVariableList[index].delBtnStatus){
					this.globalVariableList[index].delBtnStatus = true//锁住当前的 删除按钮
					this.globalVariableList[index].delTipStatus = false//提示消失
					/*请求后台删除*/
					this.$baseURL(this.$domain.cms)
					this.$get(this.$api.delGlobalVariable, {
						appid: this.appid,
						'id': row.id
					}).then(res => {
						if(res.data.code == 0){
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'success'
							});
							this.globalVariableList.splice(index, 1);//删除当前行
						}else{
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'error'
							});
						}
						this.globalVariableList[index].delBtnStatus = false//释放当前的 删除按钮
					})
					.catch(err => {})
					.finally(() => {}) 
				}
			}
		},
		/*插入上传的文件*/
		insertFile(file, index){
			// console.log(file)
			// console.log(file instanceof Array)
			if(file instanceof Array){//如果是数组的话，说明是图片
				this.globalVariableList[index].variable_val = []
				this.globalVariableList[index].variable_val.push(
					{
						name: '',
						url:  file[0].url
					}
				)

				/*图片保存到服务器*/
				// console.log(file[0].url, 111)
				// console.log(index, 222)
				// console.log(this.globalVariableList[index])
				let row = {
					id: this.globalVariableList[index].id,
					variable_val: this.globalVariableList[index].variable_val[0].url
				}
				// console.log(row)
				this.setVariableVal(index, row)

			}else{//单个文件路径

			}
		},
		/*删除上传的文件*/
		delFile(index, field){
			// console.log(field)
			if(index >= 0){//图片
				this.globalVariableList[field].variable_val.splice(index, 1)
			}else{//文件路径

			}
		},
		/*调用标签*/
		getTag(row){
			// console.log(row, 1111)
			let self = this;
			var content = row.variable_tag;
			var clipboard = new Clipboard('.tag-read', {
				text: function() {
					return "{us:global name='" + content + "'}";
				}
			});

			clipboard.on('success', e => {
				self.$message({
					message: '复制标签成功!',
					type: 'success'
				});
				//tips(this, '复制链接成功!', 'success');
				clipboard.destroy()   // 释放内存
			})
			clipboard.on('error', e => {
				// 不支持复制
				self.$message({
					message: '该浏览器不支持链接复制!',
					type: 'warning'
				});
				//tips(this, '该浏览器不支持链接复制!', 'warning');
				clipboard.destroy()    // 释放内存
			})
		}
	},
	computed: {
		...mapGetters([
			'allMenuList'
		])
	}
};
</script>

<style lang="stylus" scoped>
</style>